/*
 * Copyright (c) HiSilicon (Shanghai) Technologies Co., Ltd. 2023-2023. All rights reserved.
 */

#include "DiaglogJLinkSetting.h"
#include <QFileDialog>
#include "BurnToolCommon/Global.h"

DiaglogJLinkSetting::DiaglogJLinkSetting(QWidget *pParent)
    : QWidget(pParent),
      ui(new Ui::MenuSettingsJLink()),
      cfg(Global::GetAppConfigPath() + "\\config_" +
          Global::ChipTypeIdToString(Global::currentChipTypeId) + "\\config.ini", QSettings::IniFormat)
{
    if (ui != nullptr) {
        ui->setupUi(this);
        setWindowTitle(QObject::tr("J-Link Settings"));
        connect(ui->pbMore, &QPushButton::clicked, this, &DiaglogJLinkSetting::SlotMoreButtonClick);
        connect(ui->pbOk, &QPushButton::clicked, this, &DiaglogJLinkSetting::SlotOkButtonClick);
        connect(ui->pbCancel, &QPushButton::clicked, this, &DiaglogJLinkSetting::SlotCancelButtonClick);
    }
}

DiaglogJLinkSetting::~DiaglogJLinkSetting()
{
    if (ui != nullptr) {
        delete ui;
    }
}

void DiaglogJLinkSetting::SlotMoreButtonClick()
{
    if (ui == nullptr) {
        return;
    }
    QString filePath = QFileDialog::getExistingDirectory(this, tr("Select File"), ui->lineJLinkPath->text());
    if (!filePath.isEmpty()) {
        ui->lineJLinkPath->setText(filePath);
    }
}

void DiaglogJLinkSetting::SlotOkButtonClick()
{
    if (ui == nullptr) {
        return;
    }
    cfg.setValue(CFG_JLINK_PATH, ui->lineJLinkPath->text());
    this->close();
}

void DiaglogJLinkSetting::SlotCancelButtonClick()
{
    this->close();
}

void DiaglogJLinkSetting::showEvent(QShowEvent *)
{
    if (ui == nullptr) {
        return;
    }
    ui->lineJLinkPath->setText("C:\\Program Files (x86)\\SEGGER\\JLink\\");
    QString str = cfg.value(CFG_JLINK_PATH).toString();
    if (!str.isEmpty() && QDir(str).exists()) {
        ui->lineJLinkPath->setText(str);
    }
}
